const dotenv = require('dotenv');
const md5 = require('js-md5');
const axios = require('axios');
dotenv.config();

class FeishuService {
  constructor() {
    // 从环境变量读取飞书配置
    //添加从环境变量读取HospitalCode值的代码
    this.hospitalCode = process.env.HOSPITAL_CODE || '';
    this.appId = process.env.FEISHU_APP_ID || '';
    this.appKey = process.env.FEISHU_APP_KEY || ''; // 注意：这里使用appKey而不是appSecret
    this.baseUrl = process.env.FEISHU_BASE_URL_INNER || process.env.FEISHU_BASE_URL_OUT ;
    this.secretKey = '';
    this.requestTime = 0;
  }

  // 获取签名
  getSecretKey() {
    // 添加SecretKey有效性判断，当this.requestTime与当前时间差小于10分钟时，说明签名未过期，直接返回
    const currentTime = new Date().getTime();
    if (currentTime - this.requestTime < 10 * 60 * 1000 && this.secretKey) {
      return this.secretKey;
    }

    this.requestTime = new Date().getTime();
    this.secretKey = md5.base64(this.appId + this.appKey + this.requestTime);
    return this.secretKey;
  }

  

  // 发送文本消息
  async sendTextMessage(receiveId,  content) {
    try {

      this.getSecretKey();
      const response = await axios.post(
        `${this.baseUrl}/systemManager/feishu/api/batchSendMessage`,
        {
          oaAccounts: [receiveId],
          content: JSON.stringify({ text: content }),
          msgType: 'text'
        },
        {
          headers: {
            'HospitalCode': this.hospitalCode,
            'AppId': this.appId,
            'SecretKey': this.secretKey,
            'RequestTime': this.requestTime,
            'Content-Type': 'application/json'
          }
        }
      );

      // 检查响应数据格式
      if (!response.data) {
        throw new Error('无效的响应数据');
      }

      if (response.data.code !== 0) {
        throw new Error(`发送消息失败: ${response.data.message || '未知错误'}`);
      }

      return response.data.message || '发送成功';
    } catch (error) {
      console.error('发送飞书消息错误:', error.message);
      throw error;
    }
  }

  // 发送富文本消息
  async sendRichTextMessage(receiveId,  title, elements) {
    try {
      this.getSecretKey();
      const response = await axios.post(
        `${this.baseUrl}/systemManager/feishu/api/batchSendMessage`,
        {
          oaAccounts: [receiveId],
          content: JSON.stringify({
            title: title,
            elements: elements
          }),
          msgType: 'post'
        },
        {
          headers: {
            'HospitalCode': this.hospitalCode,
            'AppId': this.appId,
            'SecretKey': this.secretKey,
            'RequestTime': this.requestTime,
            'Content-Type': 'application/json'
          }
        }
      );

      if (response.code !== 0) {
        throw new Error(`发送富文本消息失败: ${response.data.msg}`);
      }

      return response.message;
    } catch (error) {
      console.error('发送飞书富文本消息错误:', error.message);
      throw error;
    }
  }
}

module.exports = new FeishuService();